package com.heima.encrypt;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.Test;

import java.util.Date;
import java.util.UUID;

/**
 * 生成token
 */
public class Jwt {
    /**
     * jwt令牌
     */
    @Test
    public void JwtDemo(){
        String secret="itcast";//对称加密秘钥
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, secret).
                setId(UUID.randomUUID().toString()).//jwt唯一标识
                setSubject("all").
                claim("username", "zhangsan").
                claim("userId", 123).
                setIssuedAt(new Date()).
                setExpiration(new Date(System.currentTimeMillis() + 60 * 1000 * 60)).//一小时过期
                compact();
        System.out.println("token:"+token);
        //token:eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJmYmQwOWEyNS1mYjMyLTQyYWEtOTI5ZS01ZjA4NmI2ODkzZTEiLCJzdWIiOiJhbGwiLCJ1c2VybmFtZSI6InpoYW5nc2FuIiwidXNlcklkIjoxMjMsImlhdCI6MTYyMTM0NDMwMSwiZXhwIjoxNjIxMzQ3OTAxfQ.5aldT_LBj6rzsYzj3LSE4SM0vi8KrzFN482G9klyBIU
    }

    /**
     * jwt令牌校验
     */
    @Test
    public void JwtCheck(){
        String secret="itcast";
        String token="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJmYmQwOWEyNS1mYjMyLTQyYWEtOTI5ZS01ZjA4NmI2ODkzZTEiLCJzdWIiOiJhbGwiLCJ1c2VybmFtZSI6InpoYW5nc2FuIiwidXNlcklkIjoxMjMsImlhdCI6MTYyMTM0NDMwMSwiZXhwIjoxNjIxMzQ3OTAxfQ.5aldT_LBj6rzsYzj3LSE4SM0vi8KrzFN482G9klyBIU";

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
        System.out.println("claimsJws:"+claimsJws);
        System.out.println("头："+claimsJws.getHeader());
        System.out.println("载荷："+claimsJws.getBody());
        System.out.println("userid："+claimsJws.getBody().get("userId"));
        System.out.println("签名："+claimsJws.getSignature());
    }
}
